<template>
  <a-modal
    title="上传附件"
    :width="640"
    :visible="visible"
    @cancel="handleCancel"
    @ok="handleCancel"
  >
    <a-upload
      name="file"
      :multiple="true"
      :fileList="fileList"
      :customRequest="myUpload"
      :remove="myRemove"
      :before-upload="beforeUpload"
      @change="handleChange"
      accept=".doc,.docx,.xls,.xlsx,.ppt,.pptx,.pdf,.jpg,.jpeg,.png,.bmp"
      :disabled="uploadDisabled"
    >
      <a-button> <a-icon type="upload" /> Click to Upload </a-button>
    </a-upload>
    <span v-if="emptyFile">没有附件</span>
  </a-modal>
</template>

<script>
  import * as api from '../../../api/dataManage'
  export default {
    name: 'AttachmentModal',
    props: {
      attachmentType: {
        type: String,
        default: '1'
      },
      uploadDisabled: {
        type: Boolean,
        default: false
      }
    },
    data () {
      return {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 7 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 13 }
        },
        visible: false,
        // 选择行的数据 主键id
        cId: '',
        defaultFileList: [],
        fileList: []
      }
    },
    computed: {
      emptyFile () {
        return this.fileList.length === 0
      }
    },
    methods: {
      show (record) {
        this.cId = record.id
        api.Attachment({
          attachmentType: this.attachmentType,
          id: record.id
        }).then(res => {
          res.result.forEach(item => {
            const obj = {
              uid: item.id, // 文件唯一标识，建议设置为负数，防止和内部产生的 id 冲突
              name: item.attachmentName, // 文件名
              status: 'done', // 状态有：uploading done error removed
              // response: '{"status": "success"}', // 服务端响应内容
              linkProps: '{"download": "' + item.attachmentName + '"}', // 下载链接额外的 HTML 属性
              // xhr: 'XMLHttpRequest{ ... }' // XMLHttpRequest Header
              url: 'http://' + item.attachmentUrl.replace('172.19.99.162', '101.132.166.121')
            }
            this.fileList.push(obj)
          })
          this.visible = true
          console.log(this.fileList)
        })
      },
      beforeUpload (file) {
        const fileName = file.name
        const fileSize = file.size / (1024 * 1024)
        const idx = fileName.lastIndexOf('.')
        if (idx !== -1) {
          let ext = fileName.substr(idx + 1).toUpperCase()
          ext = ext.toLowerCase()
          if (ext !== 'doc' && ext !== 'docx' && ext !== 'xls' && ext !== 'xlsx' &&
            ext !== 'ppt' && ext !== 'pptx' && ext !== 'pdf' && ext !== 'jpg' &&
            ext !== 'jpeg' && ext !== 'png' && ext !== 'bmp') {
            this.$message.error(fileName + '不支持的附件格式！')
            return false
          }
        } else {
          this.$message.error(fileName + '不支持的附件格式！')
          return false
        }
        if (fileSize > 20) {
          this.$message.error(fileName + '附件大小不能超过20MB')
          return false
        }
        const _this = this
        if (this.fileList.filter(file => file.name === fileName).length > 0) {
          return new Promise(function (resolve, reject) {
            _this.$confirm({
              title: fileName + '文件名已存在，是否替换原文件？',
              onOk () { resolve(file) },
              onCancel () { }
              // onCancel () { reject(new Error('cancel')) }
            })
          })
        }
        return true
      },
      handleChange (info) {
        let fileList = [...info.fileList]
        if (info.file.status !== 'uploading') {
          console.log(info.file, info.fileList)
        }
        if (info.file.status === 'done') {
          fileList = fileList.map(file => {
            if (file.response) {
              file.url = 'http://' + file.response.result.replace('172.19.99.162', '101.132.166.121')
            }
            return file
          })
          this.$message.success(`${info.file.name} 上传成功`)
        } else if (info.file.status === 'error') {
          this.$message.error(`${info.file.name} 上传失败`)
        } else if (!info.file.status && info.file.status === undefined) {
          for (let i = 0, len = fileList.length; i < len; i++) {
            if (fileList[i].status === undefined) {
              fileList.splice(i, 1)
              i--
            }
          }
        }
        let flag = false
        if (fileList.filter(file => file.name === info.file.name).length > 1) {
          flag = true
          for (let j = 0, len2 = fileList.length; j < len2; j++) {
            if (fileList[j] && fileList[j].name === info.file.name && fileList[j].status === 'done') {
              fileList.splice(j, 1)
            }
          }
          this.fileList = fileList
        }
        if (!flag) {
          this.fileList = fileList
        }
      },
      handleCancel () {
        this.fileList = []
        this.visible = false
      },
      myUpload (action) {
        console.log(action)
        const formData = new FormData()
        formData.append('file', action.file)
        formData.append('type', this.attachmentType)
        formData.append('cId', this.cId)
        const progress = { percent: 0 }
        const intervalId = setInterval(() => {
          if (progress.percent < 100) {
            progress.percent = progress.percent + 5
            action.onProgress(progress)
          } else {
            clearInterval(intervalId)
            api.Upload(formData).then(res => {
              console.log(res)
              if (res.code === 200) {
                action.onSuccess(res)
              } else {
                action.onError()
              }
            }).catch(e => {
              action.onError(e)
            })
          }
        }, 100)
      },
      myRemove (file) {
        console.log(file)
        api.AttachmentDelete({
          type: this.attachmentType,
          cId: this.cId,
          id: file.uid
        }).then(res => {
          if (res.code === 200) {
            this.$message.success(res.result)
          } else {
            this.$message.success(res.result)
          }
        }).catch(e => {
          this.$message.success('删除失败')
        })
      },
      clearFileList () {
        this.fileList = []
      }
    }
  }
</script>

<style scoped>

</style>
